package com.example.emailWeb.Socket.Proxy;

import com.example.emailWeb.ntru.encrypt.NtruProxyParameters;
import com.example.emailWeb.ntru.encrypt.NtruProxyServer;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(IpPort.ServerPort);
        /**
         * 服务器:
         * 接受密钥协商
         *  1. 接收文件拥有者发来的r
         *  2. 接收文件请求者发来的a
         *  3. 通过r和a生成Rkab
         * 服务器接收加密的CA
         */
        while (true) {
            Socket accept = serverSocket.accept();
            PolySocketData polySocketData = receiveData(accept);
//            NtruProxyServer Server = new NtruProxyServer(NtruProxyParameters.APR2011_439);
            System.out.println(polySocketData);
            deal(polySocketData,accept);
        }
    }

    /**
     * 从输入流读取数据
     * 因为作为服务器不会主动给别人发消息，所以消息接收完毕，就关闭这个socket
     *
     * @return
     */
    public static PolySocketData receiveData(Socket socket) {
        ObjectInputStream ois = null;
        PolySocketData PSdata = null;
        try {
            ois = new ObjectInputStream(socket.getInputStream());
            PSdata = (PolySocketData) ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            /*if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }*/
            /*if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }*/
        }
        return PSdata;
    }

    /**
     * 服务器需要接收请求者也要接收文件拥有者的data
     *
     * @param polySocketData
     */
    public static void deal(PolySocketData polySocketData,Socket socket) throws IOException {
        PrimaryKey primaryKey = new PrimaryKey(polySocketData);
        NtruProxyServer Server = null;
        ProxyProcess proxyProcess = null;
        if (NtruMap.map.containsKey(primaryKey.info)) {
            proxyProcess = NtruMap.map.get(primaryKey.info);
        } else {
            Server = new NtruProxyServer(NtruProxyParameters.APR2011_439);
            proxyProcess = new ProxyProcess(Server);
        }
        //单独对文件请求者的CB回复
        if(polySocketData.encry&&polySocketData.requester){
            proxyProcess.onlyGiveCB2Requester(socket,polySocketData);
        }else {
            proxyProcess.Main(polySocketData);
        }

        NtruMap.map.put(primaryKey.info, proxyProcess);
    }
}
